#include "tcp_socket.hpp"
#include <sstream>

#define CHECE_ERS(q) if((q)==false){return -1;}

int main(int argc,char* argv[])
{
  if(argc!=2)
  {
    std::cout<<"./http_server prot\n";
    return -1;
  }

  int srv_prot=std::stoi(argv[1]);
  std::string srv_ip="0.0.0.0";

  TcpSocket lis_sock;
  CHECE_ERS(lis_sock.Socket());
  CHECE_ERS(lis_sock.Bind(srv_ip,srv_prot));

  CHECE_ERS(lis_sock.Listen());
  while(1)
  {
    TcpSocket new_sock;
    bool ret;
    ret=lis_sock.Accept(&new_sock);
    if(ret==false)
    {
      new_sock.Close();
      continue;
    }

    std::string req;
    new_sock.Recv(&req);
    size_t pos=req.find("\r\n\r\n");
    if(pos==std::string::npos)
    {
      //没有头结尾，认为头部较大
      //将响应状态码设置为 414 Request_URI Large
      return -1;
    }

    std::string header=req.substr(0,pos);//从0-pos为头部
    std::string body=req.substr(pos+4);//从pos+4到结尾为正文

    std::cout<<"header:"<<header<<std::endl;

    std::cout<<"body:"<<body<<std::endl;


    std::string rsp="<html><head><title> OK!!! </title></head><body><h1>hello world</h1></body></html>";
    std::stringstream ss;

    ss<<"HTTP/1.1 200 OK\r\n";
    ss<<"Connection: close\r\n";
    ss<<"Content-Type: text/html\r\n";
    ss<<"Content-Length: "<<req.size()<<"\r\n";
    ss<<"\r\n";
    ss<<rsp;

    std::cout<<ss.str()<<std::endl;
    new_sock.Send(ss.str());
    new_sock.Close();

  }
  lis_sock.Close();



  return 0;
}
